package com.pallass.common.service;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Transactional;

import com.pallass.common.domain.BaseDomain;
import com.pallass.common.repository.BaseRepository;

@Transactional
public abstract class BaseServiceImpl<T extends BaseDomain, ID extends Serializable> implements BaseService<T, ID> {

	public abstract BaseRepository<T, ID> getBaseDao();

	@Override
	public T findOne(ID id) {
		return getBaseDao().findOne(id);
	}

	@Override
	public List<T> findAll() {
		return getBaseDao().findAll();
	}

	@Override
	public List<T> findAll(ID[] ids) {
		List<ID> idList = Arrays.asList(ids);
		return getBaseDao().findAll(idList);
	}

	@Override
	public List<T> findAll(Specification<T> spec, Sort sort) {
		return getBaseDao().findAll(spec, sort);
	}

	@Override
	public Page<T> findAll(Pageable pageable) {
		return getBaseDao().findAll(pageable);
	}

	@Override
	public List<T> findAll(Iterable<ID> ids) {
		return getBaseDao().findAll(ids);
	}

	@Override
	public Page<T> findAll(Specification<T> spec, Pageable pageable) {
		return getBaseDao().findAll(spec, pageable);
	}

	@Override
	public long count() {
		return getBaseDao().count();
	}

	@Override
	public long count(Specification<T> spec) {
		return getBaseDao().count(spec);
	}

	@Override
	public boolean exists(ID id) {
		return getBaseDao().exists(id);
	}

	@Override
	public void save(T entity) {
		entity.setCreateTime(new Date());
		entity.setUpdateTime(new Date());
		getBaseDao().save(entity);
	}

	public void save(Iterable<T> entitys) {
		for (T entity : entitys) {
			entity.setCreateTime(new Date());
			entity.setUpdateTime(new Date());
		}
		getBaseDao().save(entitys);
	}

	@Override
	public T saveAndFlush(T entity) {
		// set createTime for new object
		if (entity.getCreateTime() == null) {
			entity.setCreateTime(new Date());
		}
		entity.setUpdateTime(new Date());
		return getBaseDao().saveAndFlush(entity);
	}

	@Override
	public void delete(ID id) {
		getBaseDao().delete(id);
	}

	@Override
	public void deleteByIds(@SuppressWarnings("unchecked") ID... ids) {
		if (ids != null) {
			for (int i = 0; i < ids.length; i++) {
				ID id = ids[i];
				this.delete(id);
			}
		}
	}

	public void deleteByIdArray(ID ids[]) {
		if (ids != null) {
			for (ID id : ids) {
				this.delete(id);
			}
		}
	}

	@Override
	public void delete(T[] entitys) {
		List<T> tList = Arrays.asList(entitys);
		getBaseDao().delete(tList);
	}

	@Override
	public void delete(Iterable<T> entitys) {
		getBaseDao().delete(entitys);
	}

	@Override
	public void delete(T entity) {
		getBaseDao().delete(entity);
	}

	@Override
	public T update(T entity) {
		return getBaseDao().saveAndFlush(entity);
	}

}
